<template>
  <div id="root">
    <el-row>
      <el-col :span="8" class="root-left">
        <h2 style="text-align: center;margin-bottom: 20px"> 公司文件上传 <span class="el-icon-upload2"></span></h2>
        <div class="grid-content">
          <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px"
                   class="demo-ruleForm">

            <el-form-item label="文件名" prop="filename">
              <el-input type="text" v-model="ruleForm.filename" autocomplete="off"></el-input>
            </el-form-item>

            <el-form-item label="文件描述" prop="desc">
              <el-input type="text" v-model="ruleForm.desc" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="文件上传" prop="file">
              <div class="el-upload-dragger">
                <el-upload
                  class="upload-demo"
                  ref="upload"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :file-list="fileobj"
                  :http-request="httpRequest"
                  :auto-upload="false">
                  <div class="el-icon-upload" style="height: 50px"></div>
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                </el-upload>
              </div>
            </el-form-item>

            <el-form-item>

              <el-button style="margin-left: 10px;" type="success" @click="submitUpload">提交
              </el-button>
              <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col :span="14" class="root-right">
        <div class="show-message">
          <el-table
            height="470"
            :data="tableData"
            style="width: 100%;"
            :default-sort="{prop: 'created', order: 'descending'}"
          >
            <el-table-column
              prop="created"
              label="上传日期"
              sortable
              width="130">
            </el-table-column>
            <el-table-column
              prop="name"
              label="文件别名"
              sortable
              width="100">
            </el-table-column>

            <el-table-column
              prop="desc"
              label="文件描述"
            >
            </el-table-column>
            <el-table-column label="操作"
                             width="110"
            >
              <template slot-scope="scope">

                <el-link targer="_blank" :href="`${download_url}?id=${scope.row.id}`">
                </el-link>
                <el-button
                  type="primary"
                  size="mini"
                  style="color: white"
                  @click="downloadfile(scope.$index, scope.row)"
                >
                  下载
                </el-button>
                <br>
                <br>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagenation">
          <el-pagination
            small
            layout="prev, pager, next"
            :total="total"
            :page-size="page_size"
            @prev-click="prevfun"
            @next-click="nextfun"
            @current-change="currentchange"
          >
          </el-pagination>
        </div>
      </el-col>
    </el-row>

  </div>
</template>

<script>
  export default {
    name: 'AdminCompanyFileView',
    data () {
      var checkTitle = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('文件名不能为空'))
        }
        callback()
      }
      var validateDesc = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('文件描述不能为空'))
        }
        callback()
      }
      var checkfile = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('文件描述不能为空'))
        }
      }
      return {
        download_url: '',
        fileobj: [],//显示上传的文件
        options: [],
        form: {
          title: '',
          content: ''
        },
        formLabelWidth: '100px',
        visited: false, //控制对话框的弹出
        autosize: { minRows: 6 },
        total: 5, //先设置给初始值，只给空字符串''会报typeerror
        //下一页
        next: '',
        //上一页
        prev: '',
        //每页总数
        page_size: 1,//先设置给初始值，只给空字符串''会报typeerror
        //展示的数据
        tableData: [],
        ruleForm: {
          file: ''
        },
        rules: {
          part: [
            {
              required: true,
              message: '请选择通知的部门！！',
              trigger: 'change'
            }
          ],
          filename: [
            {
              validator: checkTitle,
              trigger: 'blur'
            }
          ],
          descs: [
            {
              validator: validateDesc,
              trigger: 'blur'
            }
          ],
          desc: [
            {
              validator: checkfile,
              trigger: 'blur'

            }
          ]

        }
      }
    },
    mounted () {
      this.download_url = this.$settings.base_url + '/user/downloadfile/'
      //获取公司文件
      this.get_data()
      //获取部门信息
      this.get_part()
    },
    methods: {
      beforeAvatarUpload (file) {
        const isJPG = file.type === 'file/docx'
        const isLt2M = file.size / 1024 / 1024 < 100

        var FileExt = file.name.split('.')[1]
        if (['pdf', 'doc', 'docx'].indexOf(FileExt) === -1) {
          this.$message({
            type: 'warning',
            message: '请上传后缀名为、pdf、doc、docx.'
          })
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 100MB!')
        }
        return isJPG && isLt2M
      },
      downloadfile (index, row) {
        var arr=row.filename.split('.')
        var file_type=arr[arr.length-1]//获取文件的格式
        this.$axios({
          method: 'get', // 如果是get方法，则写“GET”
          url: this.download_url + `?id=${row.id}`,
          responseType: 'blob'
        })
          .then(res => {

            let blob = new Blob([res.data], {
              type: 'application/msword' //这里需要根据不同的文件格式写不同的参数
            })

            let eLink = document.createElement('a')
            eLink.download = `${row.name}.${file_type}` //给文件名和指定格式
            eLink.style.display = 'none'
            eLink.href = URL.createObjectURL(blob)
            document.body.appendChild(eLink)
            eLink.click()
            URL.revokeObjectURL(eLink.href)
            document.body.removeChild(eLink)
          })
          .catch(err => {
          })

      },

      get_part () {
        this.$axios({
          url: this.$settings.base_url + '/user/partforposition/',
          method: 'get'
        }).then(res => {
          if (res.data.code === 100) {
            this.options = res.data.data
          }
        })
      },
      //submit（）执行后自动调用这个函数
      httpRequest (params) {
        var FileExt = params.file.name.split('.')[1]
        //只能上传pdf格式的文件
        var file_type = ['pdf'].indexOf(FileExt) === -1
        if (file_type) {
          this.$message({
            type: 'warning',
            message: '请上传pdf格式的文件'
          })
          this.fileobj = []
          return
        }
        const isLt2M = params.file.size / 1024 / 1024 < 100
        if (!isLt2M) {
          this.$message.warning('上传的文件大小不能超过100MB')
          return
        }
        var formdata = new FormData()
        formdata.append('filename', params.file)
        formdata.append('name', this.ruleForm.filename)
        formdata.append('desc', this.ruleForm.desc)
        this.$axios({
          url: this.$settings.base_url + '/user/companyfile/',
          method: 'post',
          data: formdata
        }).then(res => {
          if (res.data.code === 100) {
            this.$message.success('文件上传成功')
            this.get_data()
            this.resetForm('ruleForm')
            this.fileobj = []
          } else if(res.data.code===300) {
            this.$message.error('上传的文件格式不是pdf')
          }else {
            this.$message.error('文件上传失败')
          }
        })
      },
      //点击提交时调用这个
      submitUpload () {
        this.$refs.upload.submit()
      },

      resetForm (formName) {
        this.$refs[formName].resetFields()
        this.fileobj = []
      },
      get_data (page = 1) {
        this.$axios({
          url: this.$settings.base_url + `/user/companyfile/?page=${page}`,
          method: 'get',
        }).then(res => {
          //获取到用户信息，赋值给变量
          this.tableData = res.data.results
          console.log(this.tableData)
          // this.prev = res.data.links.previous
          // this.next = res.data.links.next
          this.total = res.data.count
          this.page_size = res.data.page_size
        })
      },
      prevfun (value) {
        //value拿到的当前的页码,不用传递，内置的函数，自动传递要前往的页码
        this.get_data(value)
      },
      nextfun (value) {
        //value拿到页码
        this.get_data(value)
      },
      currentchange (value) {
        this.get_data(value)

      },

      handleDelete (index, row) {
        console.log(row)
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios({
            url: this.$settings.base_url + `/user/companyfile/?id=${row.id}`,
            method: 'delete',
          }).then(res => {
            if (res.data.code === 100) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.get_data()
            } else {
              this.$message.error('无此数据，无法删除')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    }
  }
</script>

<style scoped>
  .root-left {
    margin-top: 50px;
    margin-right: 50px;
  }
  .el-upload-dragger {
    width: 255px;
    text-align: center;
  }
</style>
